package cn.rulian.base.main.controller;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.rulian.base.auth.bo.User;
import cn.rulian.base.auth.service.UserService;
import cn.rulian.base.common.dto.Message;
import cn.rulian.base.common.dto.UserInfo;
import cn.rulian.base.common.util.MD5Util;
import cn.rulian.base.common.vo.TreeVo;
import cn.rulian.base.main.service.MainService;

/**
 * 登录Controller
 */

@Controller
@RequestMapping("/base/main")
public class MainController
{
	@Autowired
	MainService service;
	
	@Autowired
	UserService userService;
	
	private final Logger log = LoggerFactory.getLogger(getClass());
	
	@RequestMapping("/index")
	public String index()
	{
		return "base/main/index";
	}

	@RequestMapping("/main")
	public String main()
	{
		return "base/main/main";
	}
	
	@RequestMapping("/getMenu")
	@ResponseBody
	public List<TreeVo> getMenu(HttpServletRequest request)
	{
		HttpSession session = request.getSession();
		UserInfo userinfo = (UserInfo)session.getAttribute("userInfo");

		return service.queryResourceByUserName(userinfo.getUser().getUsername());
	}
	
	//修改密码页面
	@RequestMapping("/toUpdatePassword")
	public String toUpdatePassword() {
		return "base/main/updatePassword";
	}
	
	//修改密码
	@RequestMapping("/updatePassword")
	@ResponseBody
	public Message updatePassword(String password,String old_password,HttpSession session) 
	{
		Message rm = new Message();
		UserInfo userinfo = (UserInfo)session.getAttribute("userInfo");
		if(userinfo==null)
		{
			rm.setCode(Message._ERROR);
			rm.setMsg("登录失效！请重新登录。");
			return rm;
		}
		User user = userinfo.getUser();
		if(!user.getPassword().equals(MD5Util.MD5(old_password)))
		{
			rm.setCode(Message._ERROR);
			rm.setMsg("原始密码输入错误!!!");
			return rm;
		}
		user.setPassword(MD5Util.MD5(password));
		userService.save(user);
		rm.setMsg("密码修改成功！");
		log.info("密码修改成功！用户名：{}",user.getUsername());
		return rm;
	}
}
